<template>
	<view class="login" :class="theme">
		<!-- #ifndef MP-TOUTIAO -->
		<u-navbar title="登录" :autoBack="true" leftIconColor="#fff" :bgColor="theme == 'light' ? '#0071ff' : '#2c2c2c'"
			:safeAreaInsetTop="true" :placeholder="true" titleStyle="color:#fff">
		</u-navbar>
		<!-- #endif -->
		<!-- 账号密码登录 -->
		<view class="login-account" v-show="type == 'useraccount'">
			<view class="login-account-header">
				<view class="hello">
					<text>Hi，欢迎使用</text>
				</view>
			</view>
			<view class="">
				<u-tabs :list="radiolist1" @click="radioChange" :current="current"></u-tabs>
			</view>
			<view class="login-account-content">
				<view class="login-account-content-tip">手机号</view>
				<input v-model="phone" type="text" placeholder="请输入手机号" placeholder-class="placeholder" />
				<view class="login-account-content-tip">密码</view>
				<input v-model="password" type="password" placeholder="请输入密码" placeholder-class="placeholder" />
				<view class="login-account-content-tip">验证码</view>
				<view class="login-account-content-captcha">
					<input v-model="verificationCode" style="width: 100%;" type="text" placeholder="请输入验证码" placeholder-class="placeholder" />	
					<image class="captchaImg" :src="captchaImg" @tap="getCaptcha">
				</view>
				<view class="login-account-content-tip link" @tap="type = 'register'">还没有账号？快去注册吧</view>
				<button type="button" @click="login(0)">
					登录
				</button>
			</view>
		</view>
		<!-- //手机验证码登录 -->
		<view class="login-register" v-show="type == 'isPhonCode'">
			<view class="login-register-header">
				<view class="hello">
					<text>Hi，手机号码登录</text>
				</view>
			</view>
			<view class="">
				<!-- <u-radio-group v-model="radiovalue1" placement="row">
					<u-radio :customStyle="{margin: '16rpx'}" v-for="(item, index) in radiolist1" :key="index"
						:label="item.name" :name="item.name" @change="radioChange(item.id)">
					</u-radio>
				</u-radio-group> -->
				<u-tabs :list="radiolist1" @click="radioChange" :current="current"></u-tabs>
			</view>
			<view class="login-register-content">
				<view class="login-register-content-tip">手机号</view>
				<input v-model="phone" placeholder="用于同步平台统一身份信息" placeholder-class="placeholder" />
				<view class="login-account-content-tip">图形码</view>
				<view class="login-account-content-captcha">
					<input v-model="verificationCode" style="width: 100%" type="text" placeholder="请输入图形码" placeholder-class="placeholder" />
					<image class="captchaImg" :src="captchaImg" @tap="getCaptcha">
				</view>
				<view class="login-account-content-tip">验证码</view>
				<view class="login-account-content-captcha">
					<input v-model="MobileCode" type="text" style="width: 100%" placeholder="请输入验证码" placeholder-class="placeholder" />
					<u-button size="mini" :disabled="getCodeBtnDisable" @click="GetmobileCode(0)"
						style="margin: 0rpx;padding: 0rpx;width: 220rpx;font-size: 10px;background-color: aliceblue;color: #53887e;border-radius: 15rpx;">{{ codeBtnWord }}</u-button>
				</view>
				<view class="login-account-content-tip link" @tap="type = 'register'">还没有账号？快去注册吧</view>
				<button type="button" @click="login(1)">登录</button>
			</view>
		</view>
		<!-- 注册 -->
		<view class="login-register" v-show="type == 'register'">
			<view class="login-register-header">
				<view class="hello">
					<text>Hi，欢迎注册</text>
				</view>
			</view>
			<view class="login-register-content">
				<view class="login-register-content-tip">手机号</view>
				<input v-model="phone" placeholder="用于同步平台统一身份信息" placeholder-class="placeholder" />

				<view class="login-register-content-tip">密码</view>
				<input v-model="password" type="password" placeholder="请输入密码" placeholder-class="placeholder" />

				<view class="login-account-content-tip">图形码</view>
				<view class="login-account-content-captcha">
					<input v-model="verificationCode" style="width: 100%;" type="text" placeholder="请输入图形码"
						placeholder-class="placeholder" />
					<image class="captchaImg" :src="captchaImg" @tap="getCaptcha">
				</view>
				<view class="login-account-content-tip">验证码</view>
				<view class="login-account-content-captcha">
					<input v-model="MobileCode" type="text" style="width: 100%" placeholder="请输入验证码" placeholder-class="placeholder" />
					<u-button size="mini" :disabled="getCodeBtnDisable" @click="GetmobileCode(1)"
						style="margin: 0rpx;padding: 0rpx;width: 220rpx;font-size: 10px;background-color: aliceblue;color: #53887e;border-radius: 15rpx;">{{ codeBtnWord }}</u-button>
				</view>
				<view class="login-register-content-tip link" @tap="type = 'useraccount';current = 0">已有账号，前往登录</view>
				<button type="button" @click="register()">注册</button>
			</view>
		</view>
		<!-- 微信小程序登录 -->
		<view class="login-wechat" v-show="type == 'miniprogram'">
			<!-- 内容区域 -->
			<view class="login-wechat__wrapper">
				<view class="login-wechat__sub-img">
					<image src="/static/login.png"></image>
				</view>
				<!-- 标题 -->
				<view class="login-wechat__title">授权登录</view>
				<!-- tips -->
				<view class="login-wechat__sub-title">
					一键授权登录，完整功能体验
				</view>
				<!-- 保存按钮 -->
				<view class="login-wechat__submit-btn" @tap="getLoginCode">
					一 键 登 录
				</view>
			</view>
		</view>
		<!-- 微信授权头像昵称 -->
		<wx-user-info-modal v-model="userInfoShow" :currentUserInfo="userInfo" @updated="updatedUserInfo" />
	</view>
</template>

<script>
	import requestConfig from "@/config/request.js";
	import WxUserInfoModal from "@/uni_modules/tuniaoui-wx-user-info/components/tuniaoui-wx-user-info/tuniaoui-wx-user-info.vue";
	import logVue from "../main/chat/log.vue";

	export default {
		data() {
			return {
				codeBtnWord: "获取验证码", // 获取验证码按钮文字
				waitTime: 30, // 获取验证码按钮失效时间
				getCodeBtnDisable: false,
				MobileCode: '',

				type: "useraccount",
				invitation: "",
				nickname: "",
				password: "",
				phone: "",
				captcha: '',
				verificationCode: '',
				passwordV: "",
				disabled: false,
				userInfoShow: false,
				userInfo: {
					avatar: "",
					nickname: "",
				},
				uuid: '',
				captchaImg: '',
				radiolist1: [{
						name: '账号登录',
						id: 0
					},
					{
						name: '手机验证码登录',
						id: 1
					}
				],
				// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
				radiovalue1: '账号登录',
				current:0
			};
		},
		components: {
			WxUserInfoModal,
		},
		onLoad(e) {
			// #ifdef H5
			this.type = e.type || 'useraccount'; // 默认为账号密码登录
			// #endif
			// #ifdef MP-WEIXIN
			this.type = e.type || 'miniprogram'; // 默认为账号密码登录
			// #endif
		},
		onShow() {
			this.getCaptcha()
			this.invitation = uni.getStorageSync('invitation') || ''
			// #ifdef H5
			if (this.invitation) {
				this.type = 'register'
			}
			// #endif
		},
		methods: {
			radioChange(n) {
				// console.log(n)
				if (n.index == 0) {
					this.type = 'useraccount'
					this.current = 0
				} else {
					this.type = 'isPhonCode'
					this.current = 1
				}
			},
			//获取图形验证码
			async getCaptcha() {
				this.captcha = ''
				const {
					data
				} = await uni.$u.http.get("/captchaImage");
				if (data.status === 200) {
					this.uuid = data.data.uuid
					this.captchaImg = "data:image/png;base64," + data.data.img
				}
			},
			// 获取code
			getLoginCode() {
				// uni.login({
				// 	success: (e) => {
				// 		this.login(e);
				// 	},
				// });
			},
			//获取手机验证码
			async GetmobileCode(e) {
				if (!this.phone || !this.verificationCode) {
					return uni.showToast({title: "手机号 和 图形验证码不能为空",icon: "none"});
				}
				const {data} = await uni.$u.http.post("/user/register/verify", {phone: this.phone,uuid: this.uuid,type:e,verificationCode: this.verificationCode});
				if (data.code == 200) {
					let that = this;
					that.waitTime--;
					that.getCodeBtnDisable = true;
					this.codeBtnWord = `${this.waitTime}s 后重新获取`;
					let timer = setInterval(function() {
						if (that.waitTime > 1) {
							that.waitTime--;
							that.codeBtnWord = `${that.waitTime}s 后重新获取`;
						} else {
							clearInterval(timer);
							that.codeBtnWord = "获取验证码";
							that.getCodeBtnDisable = false;
							that.waitTime = 31;
						}
					}, 1000);
				} else {
					uni.showToast({title: data.msg || '操作失败',icon: "none"});
				}
				return
			},
			// 注册
			async register() {
				uni.showLoading({title: '注册中～',mask: true})
				const {data} = await uni.$u.http.post("/user/reg", {
					account: this.phone,
					password: this.password,
					smsCode: this.MobileCode,
					uuid: this.uuid,
					imgCode: this.verificationCode,
					inviteCode: null,
				});
				uni.hideLoading()
				if (data.code == 200) {
					// uni.removeStorageSync('invitation')
					this.userInfo = data.data;
					uni.setStorageSync("appToken", data.data.token);
					uni.setStorageSync("userInfo", data.data.user);
					return uni.switchTab({url: "/pages/main/chat/index"});
				} else {
					uni.showToast({title: data.msg, icon: "none"});
				}
			},
			// 微信登录
			async login(e) {
				uni.showLoading({title: '登录中～',mask: true})
				let rows = ''
				if (e == 0) {
					const {data} = await uni.$u.http.post("/user/login", {
						phone: this.phone,
						password: this.password,
						uuid: this.uuid,
						catchaCode: this.verificationCode
					});
					rows = data
				}else{
					const {data} = await uni.$u.http.post("/user/login", {
						phone: this.phone,
						smsCode: this.MobileCode,
						catchaCode: this.verificationCode
					});
					rows = data
				}
				console.log(rows)
				uni.hideLoading()
				if (rows.code == 200) {
					this.userInfo = rows.data;
					uni.setStorageSync("appToken", rows.data.token);
					// #ifdef MP-WEIXIN
					// if (!this.userInfo.avatar || !this.userInfo.nickname) {
					// 	return (this.userInfoShow = true);
					// }
					// #endif
					uni.setStorageSync("userInfo", rows.data.user);
					uni.showToast({title: rows.data,icon: "none"});
					return uni.switchTab({url: "/pages/main/chat/index",});
					// this.loginBackPage()
				} else {
					uni.showToast({title: rows.data,icon: "none"});
					this.getCaptcha()
				}
			},
			uploadAvatar(e) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: requestConfig.baseURL + "/app/base/comm/upload",
						filePath: e.avatar,
						name: "file",
						success: (res) => {
							const fileData = JSON.parse(res.data);
							if (fileData.code == 1000) {
								resolve(fileData.data);
							} else {
								uni.showToast({
									title: "头像上传失败，请重试～",
									icon: "none"
								});
								throw "头像上传失败，请重试～";
							}
						},
					});
				});
			},
			// 退回上一页 如果没有则跳转首页
			loginBackPage() {
				const tabbar = uni.getStorageSync('tabbar')
				uni.switchTab({
					url: tabbar[0].pagePath,
				});
			},
			async updatedUserInfo(e) {
				this.userInfo = {
					...this.userInfo,
					...e,
					avatar: await this.uploadAvatar(e),
				};
				try {
					uni.showLoading({
						title: '登录中～',
						mask: true
					})
					const {
						data
					} = await uni.$u.http.post("/app/user/info/update", this.userInfo);
					uni.hideLoading()
					if (data.code == 1000) {
						uni.setStorageSync("userInfo", this.userInfo);
						this.loginBackPage()
					} else {
						uni.showToast({
							title: data.message,
							icon: "none"
						});
					}
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: JSON.stringify(e),
						icon: "none"
					});
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.login {
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background: var(--bg);

		&-register {
			&-header {
				padding: 50rpx 0 !important;
			}
		}

		&-account,
		&-register {
			width: 600rpx;

			&-header {
				padding: 0rpx 0 70rpx 0;

				font-weight: bold;

				.hello {
					font-size: 50rpx;
					font-weight: 400;
					display: flex;
					color: var(--black);
					align-items: center;
				}
			}

			&-content {
				input {
					border: 0;
					color: var(--black);
					border-bottom: 1px solid #ccc;
					margin: 36rpx 0rpx;
					padding-bottom: 4rpx;
				}

				.placeholder {
					// color: #c0c3cb;
					// font-size: 32rpx;
					// height: 80rpx;
				}

				&-tip {
					font-size: 28rpx;
					margin: 25rpx 0 0 0rpx;
					color: var(--black);

					&.link {
						color: $uni-color-primary;
					}
				}

				&-captcha {
					display: flex;

					.captchaImg {
						background: #000;
						height: 74rpx;
						width: 200rpx;
					}

				}

				button {
					margin-top: 50rpx;
					height: 80rpx;
					background: $uni-color-primary;
					color: #fff;
					border-radius: 45rpx;
					font-size: 32rpx;
					line-height: 80rpx;
				}
			}

			&-footer {}
		}

		&-wechat {
			padding: 0;
			width: 600rpx;

			/* title */
			&__title {
				font-size: 34rpx;
				color: var(--font-black);
			}

			/* sub-title */
			&__sub-title {
				font-size: 26rpx;
				color: #aaaaaa;
				margin-top: 16rpx;
				padding-bottom: 30rpx;
			}

			/* sub-img */
			&__sub-img {
				text-align: center;

				image {
					width: 300rpx;
					height: 300rpx;
				}
			}

			/* 保存按钮 */
			&__submit-btn {
				background-color: $uni-color-primary;
				color: #ffffff;
				margin-top: 30rpx;
				border-radius: 10rpx;
				padding: 25rpx;
				font-size: 32rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				&.disabled {
					background-color: #e6e6e6;
				}
			}
		}
	}
</style>